﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace com.tdb.foundation
{
    public class UIManager : MonoBehaviour
    {
        private static UIManager _instance;

        [SerializeField] private Transform _root;

        /// <summary>
        ///     界面栈
        /// </summary>
        private Stack<BaseView> _viewStack;

        public static UIManager Instance
        {
            get
            {
                if (_instance == null) Debug.LogError("Can`t find UIManager in current scense!");
                return _instance;
            }
        }

        private void Awake()
        {
            _instance = this;
            _viewStack = new Stack<BaseView>();
            DontDestroyOnLoad(this);
        }

        public void OpenView(BaseContext context, OpenType openType = OpenType.Normal)
        {
            if (_viewStack.Count > 0)
            {
                var currentView = _viewStack.Peek();
                switch (openType)
                {
                    case OpenType.Normal:
                        currentView.OnPause();
                        break;
                    case OpenType.Single:
                        CloseAllView();
                        break;
                    default:
                        throw new ArgumentOutOfRangeException("openType", openType, null);
                }
            }

            var go = Singleton<GameResManager>.Instance.Load<GameObject>(context.ViewType.Path);
            go = Instantiate(go);
            go.transform.SetParent(_root, false);
            var newView = go.GetComponent<BaseView>();
            _viewStack.Push(newView);
            newView.OnEnter(context, null);
        }

        /// <summary>
        ///     关闭当前栈中所有界面
        /// </summary>
        private void CloseAllView()
        {
            while (_viewStack.Count > 0)
            {
                var go = _viewStack.Pop();
                go.OnExit(() => { });
            }
        }


        private void CloseView(GameObject go)
        {
            Destroy(go.gameObject);
        }
    }

    public enum OpenType
    {
        Normal = 0,
        Single = 1
    }
}